package com.uphone.magicleafteacher.pro.activity;

import android.Manifest;
import android.arch.lifecycle.LifecycleOwner;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.radish.baselibrary.Intent.IntentData;
import com.radish.framelibrary.view.glide.GlideUtils;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.uphone.magicleafteacher.MyApp;
import com.uphone.magicleafteacher.R;
import com.uphone.magicleafteacher.base.BaseGActivity;
import com.uphone.magicleafteacher.base.OnPermissionCallBack;
import com.uphone.magicleafteacher.http.ApiService;
import com.uphone.magicleafteacher.http.FailureConsumer;
import com.uphone.magicleafteacher.http.RequestBodyUtil;
import com.uphone.magicleafteacher.http.RxSchedulers;
import com.uphone.magicleafteacher.http.SuccessfulConsumer;
import com.uphone.magicleafteacher.util.CommonUtil;
import com.uphone.magicleafteacher.util.GsonUtils;
import com.uphone.magicleafteacher.util.PictureSelectUtils;
import com.uphone.magicleafteacher.vo.AdviserEvent;
import com.uphone.magicleafteacher.vo.TmentDetailBean;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class TestDetailsActivity extends BaseGActivity {
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.frame_head)
    FrameLayout frameHead;
    @BindView(R.id.text_student_na)
    TextView textStudentNa;
    @BindView(R.id.text_student_age)
    TextView textStudentAge;
    @BindView(R.id.text_student_class)
    TextView textStudentClass;
    @BindView(R.id.text_time)
    TextView textTime;
    @BindView(R.id.text_address)
    TextView textAddress;
    @BindView(R.id.help_feedback)
    EditText helpFeedback;
    @BindView(R.id.max_num)
    TextView maxNum;
    @BindView(R.id.img_upload)
    ImageView imgUpload;
    @BindView(R.id.button_save)
    Button buttonSave;
    @BindView(R.id.iv_xing)
    ImageView ivXing;
    @BindView(R.id.tv_bei)
    TextView tvBei;
    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @IntentData
    private int id;
    @IntentData
    private int status;
    private String resultPic;
    private boolean hasFile;


    @Override
    protected void initBundle() {

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_test_details;
    }

    @Override
    protected void initView() {
        checkStatus(status, "");
    }

    @Override
    protected void initTitle() {
        initTitle("详情");
    }

    @Override
    protected void initData() {
        MyApp.apiService(ApiService.class)
                .appointmentDetail(id + "")
                .compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    showLoading();
                })
                .doFinally(() -> {
                    closeLoading();
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        TmentDetailBean tmentDetailBean = GsonUtils.getGson().fromJson(jsonObject, TmentDetailBean.class);
                        if (tmentDetailBean != null && tmentDetailBean.getAppointDetail() != null) {
                            loadData(tmentDetailBean.getAppointDetail());
                        }
                    }
                }, new FailureConsumer());
    }

    private void loadData(TmentDetailBean.AppointDetailBean bean) {
        checkStatus(bean.getTestStatus(), bean.getTestPic());
        textStudentNa.setText(CommonUtil.getStr(bean.getStudentName()));
        textStudentAge.setText(CommonUtil.getStr(bean.getAge() + ""));
        textStudentClass.setText(CommonUtil.getStr(bean.getGradeName()));
        textAddress.setText(CommonUtil.getStr(bean.getAddress()));
        textTime.setText(CommonUtil.getStr(bean.getAppointDate()));
        tvBei.setText(CommonUtil.getStr(bean.getRemark()));
        helpFeedback.setText(CommonUtil.getStr(bean.getTestRes()));
        GlideUtils.getInstance().loadCircleImage(this, CommonUtil.getImageUrl(bean.getHeadPhoto()), ivHead);
        if (bean.getGender() == 1) {
            Glide.with(this).load(R.drawable.ic_man).into(ivXing);
        } else {
            Glide.with(this).load(R.drawable.ic_woman).into(ivXing);
        }
    }

    private void checkStatus(int testStatus, String pic) {
        status = testStatus;
        this.resultPic = pic;
        if (status == 1) {//已经测试
            buttonSave.setVisibility(View.GONE);
            helpFeedback.setEnabled(false);
            hasFile(true, CommonUtil.getImageUrl(pic));
            ivDelete.setVisibility(View.GONE);
        } else {
            buttonSave.setVisibility(View.VISIBLE);
            hasFile(false, R.mipmap.upload_image);
        }
    }

    @Override
    protected void initListener() {
        maxNum.setText(0 + "/80");
        helpFeedback.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                maxNum.setText(editable.toString().length() + "/80");

            }
        });
    }

    @OnClick({R.id.img_upload, R.id.iv_delete, R.id.button_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_upload:
                if (hasFile) {
                    if (ivDelete.getVisibility() == View.VISIBLE) {
                        if (workPic != null)
                            CommonUtil.openBigPic(workPic.getPath());
                    } else {
                        CommonUtil.openBigPic(CommonUtil.getImageUrl(resultPic));
                    }
                } else {
                    //选择图片
                    selectPic();
                }
                break;
            case R.id.iv_delete:
                hasFile(false, R.mipmap.upload_image);
                break;
            case R.id.button_save:
                save();
                break;
        }
    }

    private void save() {
        if (CommonUtil.checkViewEmpty("请输入指导建议", helpFeedback)) {
            return;
        }
        if (workPic == null || TextUtils.isEmpty(workPic.getPath()) || !new File(workPic.getPath()).exists()) {
            ToastUtils.showShort("请选择测试结果");
            return;
        }
        Map<String, RequestBody> params = new HashMap<>();
        params.put("teacherId", RequestBodyUtil.convertToRequestBody(CommonUtil.getTeacherId()));
        params.put("appointStuId", RequestBodyUtil.convertToRequestBody(id + ""));
        params.put("testRes", RequestBodyUtil.convertToRequestBody(helpFeedback.getText().toString().trim() + ""));

        MultipartBody.Part part = RequestBodyUtil.filesToMultipartBodyPart("file", new File(workPic.getPath()));
        MyApp.apiService(ApiService.class)
                .addTestRes(params, part)
                .compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    showLoading();
                })
                .doFinally(() -> {
                    closeLoading();
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        EventBus.getDefault().post(new AdviserEvent());
                        ToastUtils.showShort("提交成功");
                        initData();
                    }
                }, new FailureConsumer());
    }

    private int picNum = 1;
    private LocalMedia workPic;

    private void selectPic() {
        getPermission(new OnPermissionCallBack() {
            @Override
            public void permissionPass(String[] permissions) {
                PictureSelectUtils.openMultiplePicture(TestDetailsActivity.this, new ArrayList<>()
                        , picNum, false, 0, 0, PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void permissionRefuse(String[] permissions) {

            }
        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(intent);
                if (selectList != null && selectList.size() > 0) {
                    workPic = selectList.get(0);
                    hasFile(true, workPic.getPath());
                }
                break;
            default:
                break;
        }
    }

    private void hasFile(boolean flag, Object image) {
        this.hasFile = flag;
        ViewGroup.LayoutParams params = imgUpload.getLayoutParams();
        if (flag) {
            ivDelete.setVisibility(View.VISIBLE);
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = SizeUtils.dp2px(444);
        } else {
            workPic = null;
            ivDelete.setVisibility(View.GONE);
            params.width = SizeUtils.dp2px(105);
            params.height = SizeUtils.dp2px(135);
        }
        imgUpload.setLayoutParams(params);
        GlideUtils.getInstance().loadCornerImage(this, image, SizeUtils.px2dp(8), imgUpload);
    }
}
